package com.changgou.item.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.pojo.FastDFSFile;
import com.changgou.file.util.FastDFSClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * 文件管理
 */
@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    //打印日志
    private Logger logger = LoggerFactory.getLogger(FileController.class);

    /**
     * 上传文件
     * @param file
     * @return 返回对象
     */
    @PostMapping("/uploadFile")
    public Result uploadFile(MultipartFile file){

        //1:创建文件对象
        try {
            FastDFSFile fastDFSFile = new
                    FastDFSFile(file.getOriginalFilename(),file.getBytes(), FilenameUtils.getExtension(file.getOriginalFilename()));
            //2:上传文件
            String path = FastDFSClient.uploadFile(fastDFSFile);
            //3:获取文件的访问路径
            return new Result(true, StatusCode.OK,"上传成功",FastDFSClient.getTrackerUrl() + path);

        } catch (IOException e) {
            e.printStackTrace();

        }

        return null;
    }

    @GetMapping
    public Result downFile() {
        String path = "group1/M00/00/00/wKjIgF2bDIaAShogAARqUAwmh3I349.jpg";
        try {
            String trackerUrl = FastDFSClient.getTrackerUrl();
            InputStream inputStream = FastDFSClient.downFile(path);

            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            byte[] in2b = swapStream.toByteArray();

            IOUtils.write(in2b, new FileOutputStream("C:\\Users\\ANG.YU\\Pictures\\Camera Roll\\.a.jpg"));
            return new Result(true, StatusCode.OK, "", inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "下载失败");
        }
    }


}

